package com.estronger.shopmanage.adapter.batchpg;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.estronger.shopmanage.R;
import com.estronger.shopmanage.bean.batch.BatchPgGoodsItem;
import com.estronger.shopmanage.bean.batch.BatchPgListBean;
import com.estronger.shopmanage.bean.batch.DeliverPGListData;
import com.estronger.shopmanage.bean.batch.InstallPGListData;
import com.estronger.shopmanage.bean.batch.MeasurePGListData;
import com.estronger.shopmanage.utils.CustomLinearLayoutManager;
import com.estronger.shopmanage.utils.DateUtils;
import com.estronger.shopmanage.utils.MD5Utils;
import com.estronger.shopmanage.utils.PermissionUtils;
import com.estronger.shopmanage.utils.TimeUtils;
import com.estronger.shopmanage.view.AppDialog;
import com.estronger.shopmanage.view.picker.DateTimePicker;
import com.soonfor.evaluate.base.EvalBaseAdapter;
import com.tbruyelle.rxpermissions2.Permission;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import cn.jesse.nativelogger.NLogger;

/**
 * Created by Soonfor on 2017/6/6.
 * 批量派工确认列表
 */

public class BatchPgConfirmAdapter extends EvalBaseAdapter<BatchPgConfirmAdapter.ViewHolder, BatchPgListBean> {

    Activity mActivity;
    List<BatchPgListBean> bpbList;
    AdapterListener adapterListener;
    int dataType = 0;//1-测量 2-送货 3-安装
    String thisYear = "";//今年

    public BatchPgConfirmAdapter(Activity context) {
        super(context);
        this.mActivity = context;
        this.thisYear = Calendar.getInstance().get(Calendar.YEAR) + "";
    }

    public void setAdapterListener(AdapterListener adapterListener) {
        this.adapterListener = adapterListener;
    }

    @Override
    public void notifyDataSetChanged(List<BatchPgListBean> dataList) {
        this.bpbList = dataList;
        notifyDataSetChanged();
    }

    @Override
    public BatchPgConfirmAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.adapter_pg_batch_confirm, parent, false);
        ViewHolder holder = new ViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.setData(bpbList.get(position), position);
        holder.llfGoodsShowHide.setTag(holder);
        holder.llfGoodsShowHide.setOnClickListener(showHideListener);
        holder.rlfYyTime.setTag(holder);
        initChoiseDateListener(holder.rlfYyTime, 0);
        holder.ivfCallToCustomer.setTag(holder);
        holder.ivfCallToCustomer.setOnClickListener(callOrSendListener);
        holder.ivfSendToCustomer.setTag(holder);
        holder.ivfSendToCustomer.setOnClickListener(callOrSendListener);
        if(dataType == 1) {//测量时才有导购员信息和打电话给导购员
            holder.ivfCallToSales.setTag(holder);
            holder.ivfCallToSales.setOnClickListener(callOrSendListener);
            holder.ivfSendToSales.setTag(holder);
            holder.ivfSendToSales.setOnClickListener(callOrSendListener);
        }else if(dataType == 2) {//预计安装时间是送货的时候才有的
            holder.rlfInstallTimeInSend.setTag(holder);
            initChoiseDateListener(holder.rlfInstallTimeInSend, 1);
        }
    }

    @Override
    public int getItemCount() {
        return bpbList == null ? 0 : bpbList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        public int positon;
        private TextView tvfName, tvfAddress, tvfOrderTimeT, tvfOrderTime, tvfYyTimeT, tvfMsYyTime, tvfGoodsShowHide;//通用都要显示的字段 名称、地址、下单日期（标题）、预约时间（标题）、展开隐藏文字
        private TextView tvfSales, tvfInstallTimeInSend;//导购员标题和导购员名称（测量时显示）、预计安装时间（送货时显示）,
        private ImageView ivfCallToCustomer, ivfSendToCustomer, ivfCallToSales, ivfSendToSales, ivfGoodsShowHide;
        private LinearLayout llfSales, llfGoodsShowHide;
        private RecyclerView rvfGoods;//产品明细
        private RelativeLayout rlfYyTime, rlfInstallTimeInSend;//选择预约时间、选择预计安装时间（送货派工需显示）
        private EditText etfRemark;//初步沟通输入框
        private BatchPgGoodsAdapter goodsAdapter;
        private CustomLinearLayoutManager linearLayoutManager;

        public ViewHolder(View itemView) {
            super(itemView);
            tvfName = (TextView) itemView.findViewById(R.id.tvfItemTitle);
            tvfAddress = (TextView) itemView.findViewById(R.id.tvfItemLocation);
            tvfSales = (TextView) itemView.findViewById(R.id.tvfSales);
            llfSales = itemView.findViewById(R.id.llfSales);
            tvfOrderTime = (TextView) itemView.findViewById(R.id.tvfOrderTime);

            ivfCallToCustomer = (ImageView) itemView.findViewById(R.id.ivfMCall);
            ivfCallToSales = (ImageView) itemView.findViewById(R.id.ivfMCallSales);
            ivfSendToCustomer = (ImageView) itemView.findViewById(R.id.ivfMSendms);
            ivfSendToSales = (ImageView) itemView.findViewById(R.id.ivfMSendToSales);

            rvfGoods = (RecyclerView) itemView.findViewById(R.id.rv_goods);
            rlfInstallTimeInSend = itemView.findViewById(R.id.rlfInstallTimeInSend);
            llfGoodsShowHide = itemView.findViewById(R.id.ll_goods_show_hide);
            tvfGoodsShowHide = itemView.findViewById(R.id.tv_show_hide);
            ivfGoodsShowHide = itemView.findViewById(R.id.iv_show_hide);

            tvfOrderTimeT = (TextView) itemView.findViewById(R.id.tvfOrderTimeT);
            tvfYyTimeT = itemView.findViewById(R.id.tvfYyTimeT);
            rlfYyTime = (RelativeLayout) itemView.findViewById(R.id.rlfYyTime);
            tvfInstallTimeInSend = itemView.findViewById(R.id.tvfInstallTimeInSend);
            tvfMsYyTime = (TextView) itemView.findViewById(R.id.tvfYyTime);
            etfRemark = (EditText)itemView.findViewById(R.id.etfRemark);
            linearLayoutManager = new CustomLinearLayoutManager(mActivity);
            linearLayoutManager.setScrollEnabled(false);
            rvfGoods.setLayoutManager(linearLayoutManager);
            goodsAdapter = new BatchPgGoodsAdapter(mActivity);
            rvfGoods.setAdapter(goodsAdapter);
        }

        public void setData(BatchPgListBean listBean, int position) {
            this.positon = position;
            if(listBean.getDatatype() == 1){//测量派工
                dataType = 1;
                MeasurePGListData data = listBean.getMeasure();
                if (data.getCstbuildname().equals("")) {
                    tvfName.setText(data.getCstname());
                } else {
                    tvfName.setText(data.cstbuildname + "-" + data.getCstname());
                }
                tvfAddress.setText(data.getAddress());
                llfSales.setVisibility(View.VISIBLE);
                tvfSales.setText(data.getNavname());
                tvfOrderTimeT.setText("下单时间:");
                tvfOrderTime.setText(data.getOrdrdate());
                tvfYyTimeT.setText("预约测量时间");
                tvfMsYyTime.setText(TimeUtils.formatToPickerTime(data.getPlanmeasuredate(), "yyyy-MM-dd HH:mm", thisYear));
                etfRemark.setHint("请输入初步沟通要求（选填）");
                etfRemark.setText(data.getFirstdemand());
                goodsAdapter.setAdapterListener(goodsAdapterListener, dataType);
                if(data.getMeasureitem().size() == 0){
                    rvfGoods.setVisibility(View.GONE);
                    llfGoodsShowHide.setVisibility(View.GONE);
                    goodsAdapter.notifyDataSetChanged(data.getMeasureitem(), position);
                }else {
                    rvfGoods.setVisibility(View.VISIBLE);
                    llfGoodsShowHide.setVisibility(View.VISIBLE);
                    if(listBean.getIsShowGoods() == 1){//展示
                        goodsAdapter.notifyDataSetChanged(data.getMeasureitem(), position);
                        tvfGoodsShowHide.setText("收起");
                        ivfGoodsShowHide.setImageResource(R.mipmap.anniu_zhankai);
                    }else {
                        goodsAdapter.notifyDataSetChanged(null, position);
                        tvfGoodsShowHide.setText("展开全部商品");
                        ivfGoodsShowHide.setImageResource(R.mipmap.anniu_shouqi);
                    }
                }
                rlfInstallTimeInSend.setVisibility(View.GONE);
                initItemTextSwitcher(etfRemark, this, 1);
            }else if(listBean.getDatatype() == 2){
                dataType = 2;
                DeliverPGListData data = listBean.getDeliver();
                if (data.getBuildname().equals("")) {
                    tvfName.setText(data.getCstname());
                } else {
                    tvfName.setText(data.buildname + "-" + data.getCstname());
                }
                tvfAddress.setText(data.getAddress());
                llfSales.setVisibility(View.GONE);
                tvfOrderTimeT.setText("开单时间:");
                tvfOrderTime.setText(data.getCdate());
                String pddate = TimeUtils.formatToPickerTime(data.getPddate(), "yyyy-MM-dd HH:mm", thisYear);
                tvfYyTimeT.setText("预约送货时间");
                tvfMsYyTime.setText(pddate);
                etfRemark.setHint("请输入备注（选填）");
                etfRemark.setText(data.getRemark());
                goodsAdapter.setAdapterListener(goodsAdapterListener, dataType);
                if(data.getDlvitem().size() == 0){
                    rvfGoods.setVisibility(View.GONE);
                    llfGoodsShowHide.setVisibility(View.GONE);
                    goodsAdapter.notifyDataSetChanged(data.getDlvitem(), position);
                }else {
                    rvfGoods.setVisibility(View.VISIBLE);
                    llfGoodsShowHide.setVisibility(View.VISIBLE);
                    if(listBean.getIsShowGoods() == 1){//展示
                        goodsAdapter.notifyDataSetChanged(data.getDlvitem(), position);
                        tvfGoodsShowHide.setText("收起");
                        ivfGoodsShowHide.setImageResource(R.mipmap.anniu_zhankai);
                    }else {
                        goodsAdapter.notifyDataSetChanged(null, position);
                        tvfGoodsShowHide.setText("展开全部商品");
                        ivfGoodsShowHide.setImageResource(R.mipmap.anniu_shouqi);
                    }
                }
                rlfInstallTimeInSend.setVisibility(View.VISIBLE);
                initItemTextSwitcher(etfRemark, this, 2);
            }else if(listBean.getDatatype() == 3){
                dataType = 3;
                InstallPGListData data = listBean.getInstall();
                if (data.getCstbuildname().equals("")) {
                    tvfName.setText(data.getCstname());
                } else {
                    tvfName.setText(data.cstbuildname + "-" + data.getCstname());
                }
                tvfAddress.setText(data.getAddress());
                llfSales.setVisibility(View.GONE);
                tvfOrderTimeT.setText("预计安装时间:");
                tvfYyTimeT.setText("预约安装时间");
                String pidate = TimeUtils.formatToPickerTime(data.getPidate(), "yyyy-MM-dd HH:mm", thisYear);
                tvfOrderTime.setText(pidate);
                tvfMsYyTime.setText(pidate);
                etfRemark.setHint("请输入备注（选填）");
                etfRemark.setText(data.getRemark());
                goodsAdapter.setAdapterListener(goodsAdapterListener, dataType);
                if(data.getIstitem().size() == 0){
                    rvfGoods.setVisibility(View.GONE);
                    llfGoodsShowHide.setVisibility(View.GONE);
                    goodsAdapter.notifyDataSetChanged(data.getIstitem(), position);
                }else {
                    rvfGoods.setVisibility(View.VISIBLE);
                    llfGoodsShowHide.setVisibility(View.VISIBLE);
                    if(listBean.getIsShowGoods() == 1){//展示
                        goodsAdapter.notifyDataSetChanged(data.getIstitem(), position);
                        tvfGoodsShowHide.setText("收起");
                        ivfGoodsShowHide.setImageResource(R.mipmap.anniu_zhankai);
                    }else {
                        goodsAdapter.notifyDataSetChanged(null, position);
                        tvfGoodsShowHide.setText("展开全部商品");
                        ivfGoodsShowHide.setImageResource(R.mipmap.anniu_shouqi);
                    }
                }
                rlfInstallTimeInSend.setVisibility(View.GONE);
                initItemTextSwitcher(etfRemark, this, 3);
            }
        }
    }

    //商品列表适配器的监听
    private BatchPgGoodsAdapter.GoodsAdapterListener goodsAdapterListener = new BatchPgGoodsAdapter.GoodsAdapterListener() {
        @Override
        public void onContionChange(ArrayList<BatchPgGoodsItem> goodsItemList, int parentId) {
            try {
                BatchPgListBean listBean = bpbList.get(parentId);
                if(listBean.getDatatype() == 1){//测量
                    listBean.measure.setMeasureitem(goodsItemList);
                }else if(listBean.getDatatype() == 2){//送货
                    listBean.deliver.setDlvitem(goodsItemList);
                }else if(listBean.getDatatype() == 3){//安装
                    listBean.install.setIstitem(goodsItemList);
                }
                bpbList.set(parentId, listBean);
                adapterListener.updateListDatas(bpbList);
            }catch (Exception e){}
        }
    };
    Dialog dialog;
    //拨打电话和法发送短信
    private View.OnClickListener callOrSendListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ViewHolder vh = (ViewHolder) v.getTag();
            String cstName = vh.tvfName.getText().toString();//客户姓名
            String salesName = "";//导购员姓名
            BatchPgListBean listBean = bpbList.get(vh.positon);
            String cstphone = "";//客户手机
            String salesPhone = "";//导购员手机
            if(dataType == 1){//测量
                cstphone = listBean.getMeasure().getCstmobile();
                salesName = listBean.getMeasure().getNavname();
                salesPhone = listBean.getMeasure().getNavmobile();
            }else if(dataType == 2){
                cstphone = listBean.getDeliver().getCstmobile();
            }else if(dataType == 3){
                cstphone = listBean.getInstall().getCstmobile();
            }
            if(MD5Utils.isRightPhoneNumber(context, cstphone)){
                if(v.getId() == R.id.ivfMCall){//打电话给客户
                    if(dialog != null && dialog.isShowing()) dialog.dismiss();
                    dialog = AppDialog.createDialog(context, cstName, cstphone, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            try {
                                String phone = (String) v.getTag();
                                goToCall(phone);
                                if(dialog != null) dialog.dismiss();
                            }catch (Exception e){
                                e.fillInStackTrace();
                            }
                        }
                    }, cstphone);
                    dialog.show();
                }else if (v.getId() == R.id.ivfMCallSales){//打电话给导购员
                    if(dialog != null && dialog.isShowing()) dialog.dismiss();
                    dialog = AppDialog.createDialog(context, salesName, salesPhone, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            try {
                                String phone = (String) v.getTag();
                                goToCall(phone);
                                if(dialog != null) dialog.dismiss();
                            }catch (Exception e){
                                e.fillInStackTrace();
                            }
                        }
                    }, salesPhone);
                    dialog.show();
                }else if (v.getId() == R.id.ivfMSendms){//发短信给客户
                    Uri uri = Uri.parse("smsto:" + cstphone);
                    Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
                    context.startActivity(intent);
                }if (v.getId() == R.id.ivfMSendToSales){//发短信给导购员
                    Uri uri = Uri.parse("smsto:" + salesPhone);
                    Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
                    context.startActivity(intent);
                }
            }
        }
    };

    //跳转到打电话界面
    private void goToCall(final String phoneNumber){
        PermissionUtils.getInstance().requestPromisssions(context, new PermissionUtils.AcceptListener() {
                    @Override
                    public void grante() {
                        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNumber));
                        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                            // TODO: Consider calling
                            //    ActivityCompat#requestPermissions
                            // here to request the missing permissions, and then overriding
                            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                            //                                          int[] grantResults)
                            // to handle the case where the user grants the permission. See the documentation
                            // for ActivityCompat#requestPermissions for more details.
                            return;
                        }
                        context.startActivity(intent);
                    }

                    @Override
                    public void denial(Permission permission) {
                        NLogger.e("您拒绝了相关权限:"+permission);
                    }

                    @Override
                    public void fail() {}
                },
                Manifest.permission.CALL_PHONE,
                Manifest.permission.READ_PHONE_STATE);
    }

    //商品列表的展开与隐藏
    private View.OnClickListener showHideListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ViewHolder vh = (ViewHolder) v.getTag();
            if(bpbList.get(vh.positon).getIsShowGoods() == 1){
                bpbList.get(vh.positon).setIsShowGoods(0);
                notifyItemChanged(vh.positon);
            }else {
                bpbList.get(vh.positon).setIsShowGoods(1);
                notifyItemChanged(vh.positon);
            }
            if(adapterListener != null) adapterListener.updateListDatas(bpbList);
        }
    };

    String dialogTitle = "";
    /**
     * 日期选择点击事件
     * @param rLayout
     * @param rlType 日期类型 0-预约（测量、送货、安装）时间 1-送货派工时需安装的预计安装时间
     */
    private void initChoiseDateListener(RelativeLayout rLayout, final int rlType){
        dialogTitle = "预约时间";
        if(rlType == 1) dialogTitle = "预计安装时间";
        else if (rlType == 0){
            if(dataType == 1){dialogTitle = "预约测量时间";}
            else if(dataType == 2){dialogTitle = "预约送货时间";}
            else if(dataType == 3){dialogTitle = "预约安装时间";}
        }
        rLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final ViewHolder VH = (ViewHolder) v.getTag();
                DateUtils.onYearMonthDayTimePicker(mActivity,15, dialogTitle, new DateTimePicker.OnYearMonthDayTimePickListener() {
                    @Override
                    public void onDateTimePicked(int index, String year) {
                        if (index == 0) {
                            long nowDate = System.currentTimeMillis();
                            Date d = new Date(nowDate);
                            String s = year.replace("今天", (DateTimePicker.beforNumDay(d, 0) + DateTimePicker.getWeekOfDate(d, 0 - 1)));
                            if(s.length() < 10){
                                return;
                            }else{
                                if(rlType == 0) {
                                    VH.tvfMsYyTime.setText(s);
                                    if (adapterListener != null) {
                                        if (dataType == 1) {//测量
                                            bpbList.get(VH.positon).measure.setPlanmeasuredate(DateTimePicker.BackDateToTime(s));
                                        } else if (dataType == 2) {//送货
                                            bpbList.get(VH.positon).deliver.setPddate(DateTimePicker.BackDateToTime(s));
                                        } else if (dataType == 3) {//安装
                                            bpbList.get(VH.positon).install.setPidate(DateTimePicker.BackDateToTime(s));
                                        }
                                        adapterListener.updateListDatas(bpbList);
                                    }
                                }else {
                                    VH.tvfInstallTimeInSend.setText(s);
                                    if (adapterListener != null) {
                                        bpbList.get(VH.positon).deliver.setPidate(DateTimePicker.BackDateToTime(s));
                                        bpbList.get(VH.positon).deliver.setIfist("1");
                                    }
                                }
                            }
                        } else {
                            if (year.length() < 10) {
                                return;
                            } else {
                                if(rlType == 0) {
                                    VH.tvfMsYyTime.setText(year);
                                    if (adapterListener != null) {
                                        if (dataType == 1) {//测量
                                            bpbList.get(VH.positon).measure.setPlanmeasuredate(DateTimePicker.BackDateToTime(year));
                                        } else if (dataType == 2) {//送货
                                            bpbList.get(VH.positon).deliver.setPddate(DateTimePicker.BackDateToTime(year));
                                        } else if (dataType == 3) {//安装
                                            bpbList.get(VH.positon).install.setPidate(DateTimePicker.BackDateToTime(year));
                                        }
                                        adapterListener.updateListDatas(bpbList);
                                    }
                                }else {
                                    VH.tvfInstallTimeInSend.setText(year);
                                    if (adapterListener != null) {
                                        bpbList.get(VH.positon).deliver.setPidate(DateTimePicker.BackDateToTime(year));
                                        bpbList.get(VH.positon).deliver.setIfist("1");
                                    }
                                }
                            }
                        }
                    }
                });
            }
        });
    }

    //输入框
    private void initItemTextSwitcher(EditText editText, ViewHolder VH, final int type){
        editText.addTextChangedListener(new ItemTextSwitcher(VH, type, new AfterEditedListener() {
            @Override
            public void onAfterEdited(int position, String string) {
                try {
                    if(type == 1){//测量
                        bpbList.get(position).measure.setFirstdemand(string);
                    }else if(type == 2){//送货
                        bpbList.get(position).deliver.setRemark(string);
                    }else if(type == 3){//安装
                        bpbList.get(position).install.setRemark(string);
                    }
                    adapterListener.updateListDatas(bpbList);
                }catch (Exception e){
                    e.fillInStackTrace();
                }
            }
        }));
    }

    public interface AdapterListener {
        void onCall(String phone);//打电话
        void onSendMsg(String phone, String msg);//发短信
        //更新列表数据
        void updateListDatas(List<BatchPgListBean> listDatas);
    }
}